package com.github.mofeideyu.jacksonUtil;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;

/**
 * @author Administrator
 * @date 2024/3/29 11:02
 * @description
 */
@Slf4j
public class JacksonJsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
    static {
        //对象的所有字段全部列入序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //取消默认转换timestamps形式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //忽略空Bean转json的错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //所有的日期格式都统一为以下的格式，即yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
        //忽略 在json字符串中存在，但在java对象中不存在对应属性的情况。防止错误
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 将对象转换位字符串
     * @param objectParam 对象参数
     * @return 对象序列化后的参数
     */
    public static String toJSONString(Object objectParam) {
        try {
            return ObjectUtils.isEmpty(objectParam) ? null : objectMapper.writeValueAsString(objectParam);
        } catch (Exception e) {
            log.error("对象转JsonString失败: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 将字符串格式的数据转换为指定类型的对象
     * @param param JSON字符串
     * @param klass 转换的类型
     * @return 指定类型的对象
     * @param <T> klass
     */
    public static <T> T parseObject(String param, Class<T> klass) {
        try {
            return StringUtils.hasText(param) ? objectMapper.readValue(param, klass) : null;
        } catch (JsonProcessingException e) {
            log.error("JsonString转对象失败: {}", e.getMessage(), e);
        }
        return null;
    }


}
